import socket
import psutil
import requests
import json
import os

TOKEN="07729388d8d042c0af0403f4d30dca35"

def get_ip_addresses():
    ip_addresses = []
    for interface, addrs in psutil.net_if_addrs().items():
        for addr in addrs:
            if addr.family == socket.AF_INET:  # IPv4
                ip_addresses.append((interface, addr.address))
            elif addr.family == socket.AF_INET6:  # IPv6
                ip_addresses.append((interface, addr.address))
    return ip_addresses

def get_process_info():
    process_info = {'current_process': psutil.Process().name()}
    return process_info

def get_memory_usage():
    memory_info = {'memory_percent': psutil.virtual_memory().percent}
    return memory_info

def save_to_json(file_name, data):
    with open(file_name, 'w') as json_file:
        json.dump(data, json_file, indent=4)

def load_from_json(file_name):
    if not os.path.exists(file_name):
        return None
    with open(file_name, 'r') as json_file:
        return json.load(json_file)


def main():
    file_name = '/home/li-xiang/my_project/test/system-report/system_info.json'
    pure_ip = get_ip_addresses()
    pure_ip = [list(x)  for x in pure_ip if x[0]=='eno1']
    current_data = {
        'ip_addresses': pure_ip,
        'process_info': get_process_info(),
        'memory_usage': get_memory_usage()
    }

    previous_data = load_from_json(file_name)
    print(current_data['ip_addresses'])
    print(previous_data.get('ip_addresses'))
    if previous_data is None or current_data['ip_addresses'] != previous_data.get('ip_addresses'):
        print("SEND")
        save_to_json(file_name, current_data)
        datas = {
            "token":TOKEN,
            "title":"IP CHANGE",
            "content":current_data,
            "template":"json"
            }
        url = "http://www.pushplus.plus/send"
        try:
            response = requests.post(url, json=datas)
            print(f"POST request sent. Status code: {response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"HTTP request failed: {e}")

if __name__ == '__main__':
    main()


